<template>
  <div class="upload">
    <div class="loading" v-if="loading">
      <img
        src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/pic_upload_h@2x.png"
        alt=""
      />
    </div>

    <div class="real" v-else>
      <nav-bar>传作品</nav-bar>
      <view class="header">
        <view class="title">课程名称：{{ c_name }}</view>
        <view class="sub">章节名称：{{ l_name }}</view>
      </view>

      <img
        v-if="!tempFilePath"
        src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/btn_upload_h@2x.png"
        alt=""
        @tap="chooseImg"
      />

      <img mode="aspectFit" v-else :src="tempFilePath" alt=""  @tap="chooseImg">

      <my-button @tap="_upload" v-if="!hadUpload">上传</my-button>
    </div>
  </div>
</template>

<script>
  // import {upload} from "../../utils/uploadFile";
  import { mapActions, mapState } from 'vuex'
  import { upload } from "../../utils/uploadFile";
  import { ajax } from "../../utils/ajax";
  import { RedirectTo, ReLaunch } from "../../utils/router";
  import { audioList, baseUrl } from "../../api/url.config";
  import { Toast } from "../../utils/modal";

  export default {
  name: "index",
  data() {
    return {
      l_id:0,
      type_id:5,
      loading: true,
      tempFilePath: "",
      tempFile: {},
      hadUpload:false,
      l_name:'',
      c_name:''
    };
  },
  computed:mapState('User',['token']),
  onShow() {

  },
  onLoad(e){
    console.log(e,e.id);
    this.l_id = e.id;
    this.getInfo();
    this.getPic();
    this.playLoadingPageVoice({ voicePath: audioList[4].audio });
    setTimeout(() => {
      this.loading = false;

    }, 3000);
  },
  methods: {
    ...mapActions('Tools', ['playLoadingPageVoice', 'playContentPageVoice']),
    ajax ({ url, data = {}, method = "POST" }) {
      // console.log("ajax-query", data);
      return new Promise((resolve, reject) => {
        uni.request({
          url: baseUrl + url,
          data,
          method,
          success(res) {
            console.log("ajax-res", res.data);
            const { code, message: title } = res.data;
            uni.hideLoading();
            uni.hideToast();
            switch (code) {
              case 1:
                resolve(res.data);
                break;
              case 0:
                // Toast({ title });
                break;
              case 2:
                // Toast({
                //   title: "用户需要重新登陆",
                //   success() {
                //     setTimeout(() => {
                ReLaunch({ url: "/pages/login/auth/auth" });
              // }, 1500);
              // }
              // });
            }
          },
          fail() {
            Toast({ title: "网络错误" });

            reject("ajax fail");
          }
        });
      });
    },

  async getPic(){
      const {l_id,token} = this;
      const res = await this.ajax({
        url:'/api/user/work/picture',
        method:'GET',
        data:{l_id,token}
      });
      if (res.data) {
        this.tempFilePath = res.data;
        this.hadUpload = true
      }
    },
    async getInfo(){
      const {l_id,token} = this;
      const res = await this.ajax({
        url:'/api/user/work/info',
        method:'GET',
        data:{l_id,token}
      });
      if (res.data) {
        this.l_name = res.data.l_name;
        this.c_name = res.data.c_name;
      }
    },
    chooseImg() {
      const that = this;
      if(this.hadUpload)return;
      uni.chooseImage({
        success(res) {
          console.log(res);
          that.tempFilePath = res.tempFilePaths[0];
          that.tempFile = res.tempFiles[0];
        }
      });
    },
   async _upload(){
     const {token,l_id,tempFilePath} = this;
     if (!['png','jpg','jpeg'].includes(tempFilePath.slice(-3).toLowerCase())) {
       return  uni.showToast({title:'图片类型不正确',mask:true,icon:'none'})
     }
     const res =  await upload({filePath:tempFilePath});
     const picture = res.data;
       ajax({
       url: '/api/user/work/submit',
       method: 'POST',
       data: { token, picture, l_id }
     }).then(res=>{
         if (res.code === 1) {
           return RedirectTo({
             url: "/pages_course/course_finish/course_finish",
             query: { id:l_id, type_id:5, count: 5 }
           });
         }else {
           uni.showToast(res.message)
         }
       })
   }
  }
};
</script>

<style scoped lang="scss">
@import "../../uni";
.upload {
  .loading {
    min-height: 100vh;
    background: url("https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/bg_upload@2x.png")
      100% 100%;
    padding-top: 1px;
    img {
      display: block;
      margin: 100upx auto;
      width: 540upx;
      height: 990upx;
    }
  }
  .real {
    .header {
      padding: 40upx 50upx;
      .title {
        @include ft(36, #273c3d, 500) margin-bottom: 40upx;
      }
      .sub {
        @include ft(32, #5d6473);
      }
    }
    img {
      display: block;
      margin: 100upx auto;
      width: 590upx;
      height: 590upx;
    }
  }
}
</style>
